/**
 *  TODO fijarse que se piden muchos datos es muy paja que sea obligatorio completar
 *	todos esos campos.
 */


package ar.com.PanteraRosa.Model;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


/**
 * @desc Data access object para el model de Contact. Se encarga de la alta baja modificacion de Contact en la
 * 	bd del celular.
 * @date 01/03/2012
 * @author pantera
 *
 */

public class ContactDao 
{

    //Datos de la bd
    private static final String DATABASE_NAME = "panterarosa";
    private static final String DATABASE_TABLE = "contact";
    private static final int DATABASE_VERSION = 2;
    
    //Campos del modelo de Contact
    public static final String KEY_ROWIDCONTACT = "ContactID";
    public static final String KEY_ROWIDPADRE = "UserIDPadre";
    public static final String KEY_ROWID = "UserID";

    private SQLiteDatabase mDb;
    private DatabaseHelper mDbHelper;
    private static final String TAG = "ContactDao";

    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
        "create table "+ DATABASE_TABLE + "(" +
        		KEY_ROWIDCONTACT + " integer, " + 
        		KEY_ROWIDPADRE + " integer, " + 
        		KEY_ROWID + " integer);";

    private final Context mCtx;

    
    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS contact");
            onCreate(db);
        }
    }//fin DatabaseHelper

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public ContactDao(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the users database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public ContactDao open() throws SQLException 
    {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    /**
     * cierrala conexion de la bd
     */
    public void cerrar() 
    {
        mDbHelper.close();
    }


    /**
     * Create a new user using the title and body provided. If the user is
     * successfully created return the new rowId for that user, otherwise return
     * a -1 to indicate failure.
     * 
     * @param contactid
     * @param useridpadre
     * @param userid
     * @return -1 if failed
     */
    public long crear(long contactid, long useridpadre, long userid){
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ROWIDCONTACT, contactid);
        initialValues.put(KEY_ROWIDPADRE, useridpadre);
        initialValues.put(KEY_ROWID, userid);        
        
        long rdo = mDb.insert(DATABASE_TABLE, null, initialValues);
        
        return rdo;
    }

    /**
     * Delete the contact with the given usuarioPadreId y usuarioId
     * 
     * @param rowIdPadre id of contac to delete
     * @param rowId id of contact to delete
     * 
     * @return true if deleted, false otherwise
     */
    public boolean eliminar(long rowIdPadre, long rowId) {
        return mDb.delete(DATABASE_TABLE, KEY_ROWIDPADRE + "=" + rowIdPadre + "and" +  
        		KEY_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all contacts in the database
     * 
     * @return Cursor over all contact
     */
    public Cursor cargarTodos() {
        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWIDCONTACT, KEY_ROWIDPADRE, KEY_ROWID}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the contact that matches the given rowPadreId
     * 
     * @param rowIdPadre id of user to retrieve
     * @return Cursor positioned to matching user, if found
     * @throws SQLException if user could not be found/retrieved
     */
    public Cursor cargarPorId(long rowIdPadre) throws SQLException {
        Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWIDCONTACT, KEY_ROWIDPADRE, KEY_ROWID}, KEY_ROWIDPADRE + "=" + rowIdPadre, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
}
